package Socket;

import java.io.*;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;

/**
聊天室的服务器端

为了实现客户端和服务端可以互发消息。
 */
public class Server3 {
    private ServerSocket serverSocket;

    public Server3() {
        try {
            System.out.println("正在启动服务端");
            serverSocket = new ServerSocket(8088);
            System.out.println("服务器启动完毕！");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void start() {
        try {
            while (true) {
                System.out.println("等待客户端连接");
                Socket socket = serverSocket.accept();
                System.out.println( "客户端"+socket.getInetAddress()+"已经连接");
                ClientHandler handler = new ClientHandler(socket);
                Thread t = new Thread(handler);
                t.start();
            }

            /*服务器接收消息*/
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        Server3 server = new Server3();
        server.start();
    }

    /*
     * 定义内部类与客户端交互
     * */
    private class ClientHandler implements Runnable {
        private Socket socket;
        private String host;  //记录客户端IP地址

        public ClientHandler(Socket socket) {
            this.socket = socket;
        }

        @Override
        public void run() {
            try {
                //服务器接收信息
                InputStream in = socket.getInputStream();
                InputStreamReader isr = new InputStreamReader(in, StandardCharsets.UTF_8);
                BufferedReader br = new BufferedReader(isr);

                InetAddress inetAddress = socket.getInetAddress();

                //服务器发送消息
                OutputStream out=socket.getOutputStream();
                OutputStreamWriter osw=new OutputStreamWriter(out,StandardCharsets.UTF_8);
                BufferedWriter bw=new BufferedWriter(osw);
                PrintWriter pw=new PrintWriter(bw,true);

                String host=String.valueOf(inetAddress);
                String subAd=host.substring(host.lastIndexOf('.'));
                String message;
                try {
                    while ((message = br.readLine()) != null) {
                        //接收信息并打印
                        System.out.println("Client ("+subAd+") ：" + message);
                        //将消息发回给客户端
                        pw.println(subAd+"said: "+ message);
                    }
                } catch (IOException e) {
                    System.out.println("大概率是客户端"+subAd+"异常退出...");
                }
            } catch (IOException e) {

            }

        }
    }


}
